package com.kvest.sqlitetest.contentprovider;

import android.content.ContentProvider;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;
import android.text.TextUtils;
import android.util.Log;
import com.kvest.sqlitetest.datastorage.sqlitestorage.MultithreadingTestHelper;
import com.kvest.sqlitetest.datastorage.sqlitestorage.table.ProductTable;

/**
 * Created with IntelliJ IDEA.
 * User: Kvest
 * Date: 20.07.13
 * Time: 14:25
 * To change this template use File | Settings | File Templates.
 */
public class ProductContentProvider extends ContentProvider {
    private MultithreadingTestHelper helper;


    private static final int LIST_PRODUCTS_INDICATOR = 1;
    private static final int SINGLE_PRODUCT_INDICATOR = 2;
    private static final UriMatcher uriMatcher;
    static {
        uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
        uriMatcher.addURI(ProductContentProviderMetadata.AUTHORITY, "products", LIST_PRODUCTS_INDICATOR);
        uriMatcher.addURI(ProductContentProviderMetadata.AUTHORITY, "products/#", SINGLE_PRODUCT_INDICATOR);
    }

    @Override
    public boolean onCreate() {
        Log.d("KVEST_TAG", "onCreate=" + Thread.currentThread().getName());
        helper = new MultithreadingTestHelper(getContext());
        return true;
    }

    @Override
    public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
        Log.d("KVEST_TAG", "query=" + Thread.currentThread().getName());
        SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();

        switch (uriMatcher.match(uri)) {
            case LIST_PRODUCTS_INDICATOR :
                queryBuilder.setTables(ProductTable.TABLE_NAME);
                break;
            case SINGLE_PRODUCT_INDICATOR :
                queryBuilder.setTables(ProductTable.TABLE_NAME);
                queryBuilder.appendWhere(ProductTable._ID + "=" + uri.getPathSegments().get(1));
                break;
            default : throw new IllegalArgumentException("Unknown uri " + uri);
        }

        SQLiteDatabase db = helper.getReadableDatabase();
        Cursor cursor = queryBuilder.query(db, projection, selection, selectionArgs, null, null, null);
        cursor.setNotificationUri(getContext().getContentResolver(), uri);

        return cursor;
    }

    @Override
    public String getType(Uri uri) {
        switch (uriMatcher.match(uri)) {
            case LIST_PRODUCTS_INDICATOR : return ProductContentProviderMetadata.PRODUCTS_LIST_TYPE;
            case SINGLE_PRODUCT_INDICATOR : return ProductContentProviderMetadata.PRODUCTS_ITEM_TYPE;
            default : throw new IllegalArgumentException("Unknown uri " + uri);
        }
    }

    @Override
    public Uri insert(Uri uri, ContentValues contentValues) {
        Log.d("KVEST_TAG", "insert=" + Thread.currentThread().getName());
        SQLiteDatabase db = helper.getWritableDatabase();

        switch (uriMatcher.match(uri)) {
            case LIST_PRODUCTS_INDICATOR :
                Long rowId = db.insert(ProductTable.TABLE_NAME, null, contentValues);
                if (rowId > 0) {
                    getContext().getContentResolver().notifyChange(uri, null);
                    Uri result = Uri.withAppendedPath(uri, Long.toString(rowId));
                    return result;
                }
        }

        throw new IllegalArgumentException("Faild to insert row into " + uri);
    }

    @Override
    public int delete(Uri uri, String selection, String[] selectionArgs) {
        Log.d("KVEST_TAG", "delete=" + Thread.currentThread().getName());
        SQLiteDatabase db = helper.getWritableDatabase();
        boolean hasSelection = !TextUtils.isEmpty(selection);
        int deletedRows = 0;

        switch (uriMatcher.match(uri)) {
            case LIST_PRODUCTS_INDICATOR :
                deletedRows = db.delete(ProductTable.TABLE_NAME, selection, selectionArgs);
                break;
            case SINGLE_PRODUCT_INDICATOR :
                deletedRows = db.delete(ProductTable.TABLE_NAME,
                                        ProductTable._ID + "=" + uri.getPathSegments().get(1) + (hasSelection ? (" AND " + selection) : ""),
                                        hasSelection ? selectionArgs : null);
                break;
            default : throw new IllegalArgumentException("Unknown uri " + uri);
        }

        if (deletedRows > 0) {
            getContext().getContentResolver().notifyChange(uri, null);
        }

        return deletedRows;
    }

    @Override
    public int update(Uri uri, ContentValues contentValues, String selection, String[] selectionArgs) {
        Log.d("KVEST_TAG", "update=" + Thread.currentThread().getName());
        SQLiteDatabase db = helper.getWritableDatabase();
        boolean hasSelection = !TextUtils.isEmpty(selection);
        int updatedRows = 0;

        switch (uriMatcher.match(uri)) {
            case LIST_PRODUCTS_INDICATOR :
                updatedRows = db.update(ProductTable.TABLE_NAME, contentValues, selection, selectionArgs);
                break;
            case SINGLE_PRODUCT_INDICATOR :
                updatedRows = db.update(ProductTable.TABLE_NAME, contentValues,
                        ProductTable._ID + "=" + uri.getPathSegments().get(1) + (hasSelection ? (" AND " + selection) : ""),
                        hasSelection ? selectionArgs : null);
                break;
            default : throw new IllegalArgumentException("Unknown uri " + uri);
        }

        if (updatedRows > 0) {
            getContext().getContentResolver().notifyChange(uri, null);
        }
        return updatedRows;
    }

    public static class ProductContentProviderMetadata {
        public static final String AUTHORITY = "com.kvest.sqlitetest.products";
        public static final Uri PRODUCTS_URI = Uri.parse("content://" + AUTHORITY + "/products");

        public static final String PRODUCTS_LIST_TYPE = "vnd.android.cursor.dir/vnd.kvest.product";
        public static final String PRODUCTS_ITEM_TYPE = "vnd.android.cursor.item/vnd.kvest.product";
    }
}
